/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controladores;

import Controladores.exceptions.NonexistentEntityException;
import Controladores.exceptions.PreexistingEntityException;
import entidades.Pet;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author Gatoper
 */
public class PetJpaController implements Serializable {

    public PetJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Pet pet) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(pet);
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findPet(pet.getName()) != null) {
                throw new PreexistingEntityException("Pet " + pet + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Pet pet) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            pet = em.merge(pet);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = pet.getName();
                if (findPet(id) == null) {
                    throw new NonexistentEntityException("The pet with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Pet pet;
            try {
                pet = em.getReference(Pet.class, id);
                pet.getName();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The pet with id " + id + " no longer exists.", enfe);
            }
            em.remove(pet);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Pet> findPetEntities() {
        return findPetEntities(true, -1, -1);
    }

    public List<Pet> findPetEntities(int maxResults, int firstResult) {
        return findPetEntities(false, maxResults, firstResult);
    }

    private List<Pet> findPetEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Pet.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    public List<Pet> findPetByProp(String prop,String c){
        EntityManager em = getEntityManager();
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
            Root<Pet> pet = cq.from(Pet.class);
            cq.select(pet).where(cb.like(pet.<String>get(prop), "%" + c + "%"));
            Query q = em.createQuery(cq);
            return q.getResultList();
        } finally {
            em.close();
        }
    
    }
    
    public List<Pet> findPetnm(String c){
        return findPetByProp("name",c);
    }
    
    public List<Pet> findPetBySpecie(String c){
        return findPetByProp("species",c);
    }
    
    public Pet findPet(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Pet.class, id);
        } finally {
            em.close();
        }
    }

    public int getPetCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Pet> rt = cq.from(Pet.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public String findPetPrice(String name) {
        EntityManager em = getEntityManager();
        try {
            String sql = "SELECT sum(charge) FROM ((pet join medicalrecord on (pet.name=medicalrecord.PET_name)) join medicalrecord_appointment on (medicalrecord_appointment.Medicalrecord_ID=medicalrecord.ID)) join appointment on (appointment.ID=medicalrecord_appointment.appointment_ID) where pet.name like '%"+name+"%';";
            Query query = em.createNativeQuery(sql);
            List<BigDecimal> a = query.getResultList();
            BigDecimal retorno=new BigDecimal(0);
            if(a.size()>0){
                retorno=a.get(0);
            }
            return retorno.toString();
        } finally {
            em.close();
        }
    }

    public TableModel findVacines(String name) {
        EntityManager em = getEntityManager();
        Object[][] datosPet;
        try {
            String sql = "select vacine.name, vacine.dosage from ((pet join medicalrecord on (pet.name=medicalrecord.PET_name)) join medicalrecord_vacine on (medicalrecord_vacine.Medicalrecord_ID=medicalrecord.ID)) join vacine on (vacine.ID=medicalrecord_vacine.vacine_ID) where pet.name like '%"+name+"%';";
            Query query = em.createNativeQuery(sql);
            List a = query.getResultList();
            datosPet = new Object[a.size()][];
            for(int i=0;i<a.size();i++){
                datosPet[i]=(Object[])a.get(i);
            }
        } finally {
            em.close();
        }
        String[] tituloPet = new String[]{"name", "dosage"};
        return new DefaultTableModel(datosPet, tituloPet);
    }

    public TableModel findAppoitmets(String name) {
        EntityManager em = getEntityManager();
        Object[][] datosPet;
        try {
            String sql = "SELECT appointment.date, appointment.charge, appointment.notes, veterinarian.name FROM (((pet join medicalrecord on (pet.name=medicalrecord.PET_name)) join medicalrecord_appointment on (medicalrecord_appointment.Medicalrecord_ID=medicalrecord.ID)) join appointment on (appointment.ID=medicalrecord_appointment.appointment_ID)) join veterinarian on (appointment.VETERINARIAN_name=veterinarian.name) where pet.name like '%"+name+"%';";
            Query query = em.createNativeQuery(sql);
            List a = query.getResultList();
            datosPet = new Object[a.size()][];
            for(int i=0;i<a.size();i++){
                datosPet[i]=(Object[])a.get(i);
            }
        } finally {
            em.close();
        }
        String[] tituloPet = new String[]{"date","charge","notes","vet name"};
        return new DefaultTableModel(datosPet, tituloPet);
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
    
}
